import VectorLayer from 'ol/layer/Vector'
import VectorSource from 'ol/source/Vector'
import LayerGroup from 'ol/layer/Group'
import Feature from 'ol/Feature'
import { Style, Fill, Stroke } from 'ol/style'
import GeoJSON from 'ol/format/GeoJSON'
import { fromExtent } from 'ol/geom/Polygon'
import LinearRing from 'ol/geom/LinearRing'

const MapHelper = {}

MapHelper.getMap = function () {
  return window.map
}

// 擦除操作,生产遮罩范围
function erase (ft, extent) {
  const geom = ft.getGeometry()
  const type = ft.getGeometry().getType()
  var polygonRing = fromExtent(extent)
  var coords = geom.getCoordinates()
  var linearRing = ''
  if (type === 'Polygon') {
    coords.forEach(coord => {
      linearRing = new LinearRing(coord)
      polygonRing.appendLinearRing(linearRing)
    })
  }
  if (type === 'MultiPolygon') {
    coords.forEach(coord => {
      coord.forEach(bound => {
        linearRing = new LinearRing(bound)
        polygonRing.appendLinearRing(linearRing)
      })
    })
  }

  return polygonRing
}

// 根据政区geojson数据 遮罩其他区域
MapHelper.shadeOthers = function (
  geoJeson,
  title = 'shadeOthersLayer',
  fillColor = 'rgba(255,255,255, 0.9)',
  strokeColor = 'rgba(255,169,64, 1)',
  strokeWidth = 2,
  featureProjection = 'EPSG:4326',
  zIndex = 900,
  extent = [-180, -90, 180, 90]
) {
  const boundLayer = new VectorLayer({
    source: new VectorSource(),
    zIndex: zIndex,
    title: title,
    style: new Style({
      fill: new Fill({
        color: fillColor
      }),
      stroke: new Stroke({
        color: strokeColor,
        width: strokeWidth
      })
    })
  })

  var fts = new GeoJSON({
    featureProjection: featureProjection
  })
  var ft = fts.readFeaturesFromObject(geoJeson)[0]
  var converGeom = erase(ft, extent)
  var convertFt = new Feature({
    geometry: converGeom
  })
  // boundLayer.getSource().clear() // --
  boundLayer.getSource().addFeature(convertFt)
  window.map.addLayer(boundLayer)
}

// 返回第一个符合条件的图层
MapHelper.getLayer = function (name, group) {
  const layers = (group || window.map).getLayers()
  const len = layers.getLength()
  let layer = null
  for (let i = 0; i < len; i++) {
    layer = layers.item(i)
    if (layer instanceof LayerGroup) {
      const find = this.getLayer(name, layer)
      if (find) {
        return find
      }
    } else if (layer.get('title') === name) {
      return layer
    }
  }
  return null
}

export default MapHelper
